package com.itheima.controller;

import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

/**
 * 使用注解缓存
 * 1. 引入pom坐标
 * 2. 在启动类进行注解
 * 3. 在对应方法注解
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /**
     * CachePut
     * key: 可以使用result(返回值)来进行表示, 使用的是对象可以使用点来获取属性
     * @param user
     * @return
     */
    @CachePut(cacheNames = "user", key = "#result.id")
    @PostMapping
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }

    @CacheEvict(cacheNames = "user", key = "#id")
    @DeleteMapping
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }


    @CacheEvict(cacheNames = "user", allEntries = true)
	@DeleteMapping("/delAll")
    public void deleteAll(){
        userMapper.deleteAll();
    }


    /**
     * Cacheable 的使用:
     *      cacheNames key的前缀
     *      使用key来真正标注
     *      #属性值, 获取属性
     *      #root.args[0]
     * @param id
     * @return
     */
    @Cacheable(cacheNames = "user", key = "#id")
    @GetMapping
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }

}
